import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Dialogs
import Qt.labs.platform as Platform

// 玩家资料面板 - 显示在界面左上角
Rectangle {
    id: profilePanel
    // 默认尺寸，可由外部覆盖
    width: 180
    height: 100
    radius: 10
    
    // 彩虹渐变背景
    gradient: Gradient {
        orientation: Gradient.Vertical
        GradientStop { position: 0.0; color: "#FF6B9D" }
        GradientStop { position: 1.0; color: "#C44569" }
    }
    
    // 简单阴影效果（兼容性更好）
    Rectangle {
        anchors.fill: parent
        anchors.topMargin: 3
        color: "#30FF6B9D"
        radius: parent.radius
        z: -1
    }
    
    RowLayout {
        anchors.fill: parent
        anchors.margins: 8
        spacing: 8
        
        // 左侧：头像和名字
        Column {
            Layout.preferredWidth: 60
            spacing: 4
            Layout.alignment: Qt.AlignTop
            
            // 头像 - 可点击
            Rectangle {
                width: 50
                height: 50
                radius: 25
                color: "#FFFFFF"
                border.color: "#FFD700"
                border.width: 2
                anchors.horizontalCenter: parent.horizontalCenter
                
                // 判断是Emoji还是图片路径
                property bool isImageAvatar: playerModel.avatar && playerModel.avatar.startsWith("qrc:")
                
                // Emoji 头像
                Text {
                    anchors.centerIn: parent
                    text: parent.isImageAvatar ? "" : (playerModel.avatar || "🦸")
                    font.pixelSize: 30
                    visible: !parent.isImageAvatar
                }
                
                // 图片头像 - 使用圆形裁剪容器
                Rectangle {
                    anchors.fill: parent
                    anchors.margins: 2
                    radius: (width / 2)
                    visible: parent.isImageAvatar
                    clip: true
                    color: "transparent"
                    
                    Image {
                        anchors.centerIn: parent
                        width: parent.width
                        height: parent.height
                        source: parent.parent.isImageAvatar ? playerModel.avatar : ""
                        fillMode: Image.PreserveAspectCrop
                    }
                }
                
                MouseArea {
                    anchors.fill: parent
                    cursorShape: Qt.PointingHandCursor
                    onClicked: {
                        profileMenuDialog.open()
                    }
                }
            }
            
            // 名字 - 可点击编辑
            Text {
                id: nameText
                text: playerModel.name || "小勇士"
                font.pixelSize: 12
                font.bold: true
                color: "white"
                anchors.horizontalCenter: parent.horizontalCenter
                elide: Text.ElideRight
                width: parent.width
                horizontalAlignment: Text.AlignHCenter
                
                MouseArea {
                    anchors.fill: parent
                    cursorShape: Qt.PointingHandCursor
                    onClicked: {
                        nameEditorDialog.open()
                    }
                }
            }
        }
        
        // 右侧：积分、星星、勋章
        Column {
            Layout.fillWidth: true
            spacing: 4
            Layout.alignment: Qt.AlignTop
            
            // 积分行
            Row {
                id: pointsRow
                spacing: 4
                
                Text {
                    id: diamondIcon
                    text: "💎"
                    font.pixelSize: 11
                    font.bold: true
                    color: "white"
                }
                
                Text {
                    id: pointsLabel
                    text: "积分"
                    font.pixelSize: 11
                    font.bold: true
                    color: "white"
                }
                
                Text {
                    text: (playerModel.totalPoints || 0)
                    font.pixelSize: 11
                    font.bold: true
                    color: "white"
                }
            }
            
            // 星星行
            Row {
                id: starsRow
                spacing: 4
                
                Text {
                    id: starIcon
                    text: "⭐"
                    font.pixelSize: 11
                    font.bold: true
                    color: "white"
                }
                
                Text {
                    id: starsLabel
                    text: "星星"
                    font.pixelSize: 11
                    font.bold: true
                    color: "white"
                }
                
                Text {
                    text: (playerModel.totalStars || 0)
                    font.pixelSize: 11
                    font.bold: true
                    color: "white"
                }
            }
            
            // 勋章行
            Row {
                id: medalRow
                spacing: 4
                
                Text {
                    id: medalIcon
                    text: "🏅"
                    font.pixelSize: 11
                    color: "white"
                }
                
                Text {
                    id: medalLabel
                    text: "勋章"
                    font.pixelSize: 11
                    color: "white"
                }
                
                // 已获得的勋章图标 - 从新到旧，最多显示2个
                Repeater {
                    // 反转数组以显示从新到旧，只取前2个
                    model: {
                        var medals = []
                        var count = Math.min(2, playerModel.medals.length)  // 最多显示2个
                        for (var i = playerModel.medals.length - 1; i >= playerModel.medals.length - count; i--) {
                            medals.push(playerModel.medals[i])
                        }
                        return medals
                    }
                    
                    Rectangle {
                        width: 20
                        height: 20
                        radius: 10
                        color: "#FFFFFFDD"
                        border.color: "#FFB300"
                        border.width: 1.5
                        
                        property var medal: (modelData !== undefined && modelData !== null) ? modelData : ({})
                        property bool isImage: typeof medal.icon === "string" &&
                                               (medal.icon.startsWith("qrc:") || medal.icon.startsWith("file:"))
                        
                        Text {
                            anchors.centerIn: parent
                            text: parent.isImage ? "" : (parent.medal.icon || "🏅")
                            font.pixelSize: 14
                            visible: !parent.isImage
                        }
                        
                        Image {
                            anchors.fill: parent
                            anchors.margins: 2
                            source: parent.isImage ? parent.medal.icon : ""
                            visible: parent.isImage
                            fillMode: Image.PreserveAspectFit
                        }
                        
                        MouseArea {
                            anchors.fill: parent
                            hoverEnabled: true
                            cursorShape: Qt.PointingHandCursor
                            
                            ToolTip.visible: containsMouse && parent.medal && parent.medal.name !== undefined
                            ToolTip.text: (parent.medal && parent.medal.name) ? parent.medal.name : "神秘勋章"
                            
                            onClicked: {
                                medalDetailLoader.active = true
                                if (medalDetailLoader.item) {
                                    medalDetailLoader.item.open()
                                }
                            }
                        }
                    }
                }
            }
            
            // 没有勋章时的提示
            Text {
                text: playerModel.medals.length === 0 ? "还没有勋章，挑战关卡加油！" : ""
                font.pixelSize: 10
                color: "white"
                width: parent.width
                wrapMode: Text.WordWrap
                visible: playerModel.medals.length === 0
            }
        }
    }
    
    // 个人资料菜单对话框
    Dialog {
        id: profileMenuDialog
        title: "个人资料"
        anchors.centerIn: parent
        width: 200
        height: 500
        modal: true
        closePolicy: Popup.CloseOnPressOutside
        
        Column {
            anchors.fill: parent
            spacing: 15
            
            Text {
                text: "管理你的个人资料"
                font.pixelSize: 16
                font.bold: true
                color: "#C44569"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Button {
                width: parent.width
                height: 60
                text: "🎨 更换头像"
                font.pixelSize: 16
                
                onClicked: {
                    profileMenuDialog.close()
                    avatarSelectorDialog.open()
                }
            }
            
            Button {
                width: parent.width
                height: 60
                text: "✏️ 修改昵称"
                font.pixelSize: 16
                
                onClicked: {
                    profileMenuDialog.close()
                    nameEditorDialog.open()
                }
            }
            
            Button {
                width: parent.width
                height: 60
                text: "☁️ 云同步配置"
                font.pixelSize: 16
                
                onClicked: {
                    profileMenuDialog.close()
                    cloudSyncConfigDialog.open()
                }
            }

            Button {
                width: parent.width
                height: 60
                text: "📤 导出技能树"
                font.pixelSize: 16
                onClicked: {
                    profileMenuDialog.close()
                    exportFileDialog.open()
                }
            }

            Button {
                width: parent.width
                height: 60
                text: "📥 导入技能树"
                font.pixelSize: 16
                onClicked: {
                    profileMenuDialog.close()
                    importFileDialog.open()
                }
            }
            
            // 移除关闭按钮，改为点击对话框外部关闭
        }
    }
    
    // 名字编辑对话框
    Dialog {
        id: nameEditorDialog
        title: "修改昵称"
        anchors.centerIn: parent
        width: 320
        height: 180
        modal: true
        
        onOpened: {
            nameInput.text = playerModel.name
            nameInput.selectAll()
            nameInput.forceActiveFocus()
        }
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "请输入你的昵称："
                font.pixelSize: 16
                font.bold: true
            }
            
            TextField {
                id: nameInput
                width: parent.width
                font.pixelSize: 18
                placeholderText: "小勇士"
                maximumLength: 10
                
                // 回车确认
                Keys.onReturnPressed: {
                    if (nameInput.text.trim() !== "") {
                        playerModel.name = nameInput.text.trim()
                        nameEditorDialog.close()
                    }
                }
                
                Keys.onEnterPressed: {
                    if (nameInput.text.trim() !== "") {
                        playerModel.name = nameInput.text.trim()
                        nameEditorDialog.close()
                    }
                }
            }
            
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Button {
                    text: "✅ 确定"
                    font.pixelSize: 16
                    
                    background: Rectangle {
                        radius: 20
                        gradient: Gradient {
                            GradientStop { position: 0.0; color: "#4CAF50" }
                            GradientStop { position: 1.0; color: "#8BC34A" }
                        }
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font: parent.font
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        if (nameInput.text.trim() !== "") {
                            playerModel.name = nameInput.text.trim()
                            nameEditorDialog.close()
                        }
                    }
                }
                
                Button {
                    text: "❌ 取消"
                    font.pixelSize: 16
                    onClicked: nameEditorDialog.close()
                }
            }
        }
    }
    
    // 头像选择对话框
    Dialog {
        id: avatarSelectorDialog
        title: "选择你的头像"
        anchors.centerIn: parent
        width: 420
        height: 500
        modal: true
        
        // 检查是否有新头像
        property bool hasNewAvatars: false
        
        onOpened: {
            hasNewAvatars = playerModel.checkForNewAvatars()
        }
        
        Column {
            anchors.fill: parent
            spacing: 15
            
            // 标题和更新按钮
            Row {
                width: parent.width
                spacing: 10
                
                Text {
                    text: "点击选择你喜欢的头像："
                    font.pixelSize: 16
                    font.bold: true
                    anchors.verticalCenter: parent.verticalCenter
                }
                
                // 更新头像按钮
                Button {
                    text: avatarSelectorDialog.hasNewAvatars ? "🔄 更新头像" : "✓ 已是最新"
                    font.pixelSize: 14
                    enabled: avatarSelectorDialog.hasNewAvatars
                    
                    background: Rectangle {
                        radius: 15
                        color: avatarSelectorDialog.hasNewAvatars ? "#4CAF50" : "#CCCCCC"
                        opacity: parent.enabled ? 1.0 : 0.6
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font: parent.font
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        if (playerModel.updateAvatarResources()) {
                            avatarSelectorDialog.hasNewAvatars = false
                        }
                    }
                }
            }
            
            // 头像网格
            GridView {
                width: parent.width
                height: 350
                cellWidth: 70
                cellHeight: 70
                clip: true
                
                model: [
                    // 图片头像
                    "qrc:/images/avatars/custom/animal.png",
                    "qrc:/images/avatars/custom/koala.png",
                    "qrc:/images/avatars/custom/owl.png",
                    "qrc:/images/avatars/custom/paw.png",
                    "qrc:/images/avatars/custom/whale.png",
                    "qrc:/images/avatars/custom/frog.png",
                    "qrc:/images/avatars/custom/parrot.png",
                    // 英雄系列
                    "🦸", "🦹", "🥷", "🧙",
                    // 动物系列
                    "🦁", "🐯", "🐉", "🦖",
                    "🐺", "🐼", "🐨", "🐸",
                    // 表情系列
                    "😎", "🤩", "🥳", "🤗",
                    "😄", "🤓", "😆", "🥰",
                    // 运动系列
                    "⚽", "🏀", "🎮", "🎯",
                    "🚀", "✈️", "🚁", "🏎️",
                    // 科学系列
                    "🔬", "🔭", "🎨", "🎵",
                    "📚", "🎪", "🎢", "🎡"
                ]
                
                delegate: Rectangle {
                    width: 65
                    height: 65
                    radius: 32.5
                    color: playerModel.avatar === modelData ? "#FFD700" : "#FFFFFF"
                    border.color: playerModel.avatar === modelData ? "#FF6B9D" : "#E0E0E0"
                    border.width: 3
                    
                    // 判断是否为图片路径
                    property bool isImage: modelData.startsWith("qrc:")
                    
                    // Emoji 显示
                    Text {
                        anchors.centerIn: parent
                        text: parent.isImage ? "" : modelData
                        font.pixelSize: 36
                        visible: !parent.isImage
                    }
                    
                    // 图片显示 - 使用圆形裁剪容器
                    Rectangle {
                        anchors.fill: parent
                        anchors.margins: 5
                        radius: (width / 2)
                        visible: parent.isImage
                        clip: true
                        color: "transparent"
                        
                        Image {
                            anchors.centerIn: parent
                            width: parent.width
                            height: parent.height
                            source: parent.parent.isImage ? modelData : ""
                            fillMode: Image.PreserveAspectCrop
                        }
                    }
                    
                    MouseArea {
                        anchors.fill: parent
                        cursorShape: Qt.PointingHandCursor
                        
                        onClicked: {
                            playerModel.avatar = modelData
                            avatarSelectorDialog.close()
                        }
                    }
                    
                    // 选中时放大
                    scale: playerModel.avatar === modelData ? 1.1 : 1
                    
                    Behavior on scale {
                        NumberAnimation { duration: 150 }
                    }
                }
            }
            
            Button {
                text: "关闭"
                anchors.horizontalCenter: parent.horizontalCenter
                font.pixelSize: 16
                onClicked: avatarSelectorDialog.close()
            }
        }
    }
    
    // 云同步配置对话框
    Dialog {
        id: cloudSyncConfigDialog
        title: "☁️ 云同步配置"
        anchors.centerIn: parent
        width: 480
        height: 540
        modal: true
        
        onOpened: {
            giteeOwnerField.text = playerModel.giteeOwner
            giteeRepoField.text = playerModel.giteeRepo
            giteeTokenField.text = playerModel.giteeToken
        }
        
        background: Rectangle {
            color: "#F0F8FF"
            radius: 15
            border.color: "#5B9BD5"
            border.width: 3
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 15
            
            Text {
                text: "配置Gitee云端仓库"
                font.pixelSize: 18
                font.bold: true
                color: "#4169E1"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "配置后将自动同步技能树数据到云端"
                font.pixelSize: 12
                color: "#666666"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            // Gitee用户名
            Column {
                width: parent.width
                spacing: 5
                
                Text {
                    text: "Gitee用户名："
                    font.pixelSize: 14
                    font.bold: true
                }
                
                TextField {
                    id: giteeOwnerField
                    width: parent.width
                    placeholderText: "例如: zuoo"
                    font.pixelSize: 14
                }
            }
            
            // Gitee仓库名
            Column {
                width: parent.width
                spacing: 5
                
                Text {
                    text: "仓库名称："
                    font.pixelSize: 14
                    font.bold: true
                }
                
                TextField {
                    id: giteeRepoField
                    width: parent.width
                    placeholderText: "例如: LitterPutting-Data"
                    font.pixelSize: 14
                }
                
                Text {
                    text: "💡 只需输入仓库名，不要输入完整URL"
                    font.pixelSize: 11
                    color: "#999999"
                    wrapMode: Text.WordWrap
                    width: parent.width
                }
            }
            
            // Gitee Token
            Column {
                width: parent.width
                spacing: 5
                
                Text {
                    text: "私人令牌 (Token)："
                    font.pixelSize: 14
                    font.bold: true
                }
                
                TextField {
                    id: giteeTokenField
                    width: parent.width
                    placeholderText: "在Gitee生成的Personal Access Token"
                    font.pixelSize: 14
                    echoMode: TextInput.Password
                }
                
                Text {
                    text: "💡 在Gitee个人设置中生成Token，需要projects权限"
                    font.pixelSize: 11
                    color: "#999999"
                    wrapMode: Text.WordWrap
                    width: parent.width
                }
            }
            
            // 当前状态
            Rectangle {
                width: parent.width
                height: 50
                radius: 10
                color: playerModel.cloudSyncEnabled ? "#E8F5E9" : "#FFF3E0"
                border.color: playerModel.cloudSyncEnabled ? "#4CAF50" : "#FF9800"
                border.width: 2
                
                Row {
                    anchors.centerIn: parent
                    spacing: 10
                    
                    Text {
                        text: playerModel.cloudSyncEnabled ? "✅" : "⚠️"
                        font.pixelSize: 24
                        anchors.verticalCenter: parent.verticalCenter
                    }
                    
                    Text {
                        text: playerModel.cloudSyncEnabled ? "云同步已启用" : "云同步未配置"
                        font.pixelSize: 14
                        font.bold: true
                        color: playerModel.cloudSyncEnabled ? "#2E7D32" : "#E65100"
                        anchors.verticalCenter: parent.verticalCenter
                    }
                }
            }
            
            // 按钮
            Row {
                anchors.horizontalCenter: parent.horizontalCenter
                spacing: 15
                
                Button {
                    text: "💾 保存配置"
                    font.pixelSize: 15
                    
                    background: Rectangle {
                        radius: 20
                        gradient: Gradient {
                            GradientStop { position: 0.0; color: parent.pressed ? "#32CD32" : "#4CAF50" }
                            GradientStop { position: 1.0; color: parent.pressed ? "#4CAF50" : "#8BC34A" }
                        }
                    }
                    
                    contentItem: Text {
                        text: parent.text
                        color: "white"
                        font: parent.font
                        horizontalAlignment: Text.AlignHCenter
                        verticalAlignment: Text.AlignVCenter
                    }
                    
                    onClicked: {
                        playerModel.giteeOwner = giteeOwnerField.text.trim()
                        playerModel.giteeRepo = giteeRepoField.text.trim()
                        playerModel.giteeToken = giteeTokenField.text.trim()
                        cloudSyncConfigDialog.close()
                        cloudSyncSavedDialog.open()
                    }
                }
                
                Button {
                    text: "取消"
                    font.pixelSize: 15
                    onClicked: cloudSyncConfigDialog.close()
                }
            }
        }
    }
    
    // 配置保存成功对话框
    Dialog {
        id: cloudSyncSavedDialog
        title: "✅ 保存成功"
        anchors.centerIn: parent
        width: 320
        height: 200
        modal: true
        
        Column {
            anchors.fill: parent
            spacing: 20
            
            Text {
                text: "🎉"
                font.pixelSize: 48
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Text {
                text: "云同步配置已保存！\n下次启动将自动同步数据"
                font.pixelSize: 14
                horizontalAlignment: Text.AlignHCenter
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Button {
                text: "确定"
                anchors.horizontalCenter: parent.horizontalCenter
                onClicked: cloudSyncSavedDialog.close()
            }
        }
    }
    
    // 头像更新提示对话框
    Dialog {
        id: avatarUpdateDialog
        property string message: ""
        property bool isSuccess: true
        
        title: isSuccess ? "✅ 更新成功" : "❌ 更新失败"
        anchors.centerIn: parent
        width: 400
        height: 220
        modal: true
        
        background: Rectangle {
            color: "#F0F8FF"
            radius: 10
            border.color: parent.isSuccess ? "#4CAF50" : "#FF5722"
            border.width: 2
        }
        
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 20
            
            Text {
                text: avatarUpdateDialog.message
                font.pixelSize: 14
                color: "#333333"
                wrapMode: Text.WordWrap
                width: parent.width
                horizontalAlignment: Text.AlignHCenter
            }
            
            Button {
                text: "确定"
                anchors.horizontalCenter: parent.horizontalCenter
                font.pixelSize: 15
                
                background: Rectangle {
                    radius: 20
                    color: avatarUpdateDialog.isSuccess ? "#4CAF50" : "#FF5722"
                }
                
                contentItem: Text {
                    text: parent.text
                    color: "white"
                    font: parent.font
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                }
                
                onClicked: avatarUpdateDialog.close()
            }
        }
    }
    
    // 连接playerModel的头像更新信号
    Connections {
        target: playerModel
        
        function onAvatarUpdateSuccess(message) {
            avatarUpdateDialog.message = message
            avatarUpdateDialog.isSuccess = true
            avatarUpdateDialog.open()
        }
        
        function onAvatarUpdateFailed(message) {
            avatarUpdateDialog.message = message
            avatarUpdateDialog.isSuccess = false
            avatarUpdateDialog.open()
        }
    }
    
    // 勋章详情对话框
    Loader {
        id: medalDetailLoader
        source: "qrc:/qml/MedalDetailView.qml"
        active: false
        
        onLoaded: {
            item.open()
        }
    }
    
    // 勋章详情对话框引用
    property var medalDetailDialog: medalDetailLoader.item

    FileDialog {
        id: exportFileDialog
        title: "选择导出位置"
        nameFilters: ["JSON 文件 (*.json)"]
        fileMode: FileDialog.SaveFile
        currentFolder: Platform.StandardPaths.writableLocation(Platform.StandardPaths.DocumentsLocation)
        currentFile: Platform.StandardPaths.writableLocation(Platform.StandardPaths.DocumentsLocation) + "/skill_trees.json"
        onAccepted: {
            var p = exportFileDialog.selectedFile || exportFileDialog.fileUrl
            if (p) {
                var ok = skillModel.exportSkillTrees(p)
                fileOpResultDialog.message = ok ? "导出成功" : "导出失败"
                fileOpResultDialog.open()
            }
        }
    }

    FileDialog {
        id: importFileDialog
        title: "选择要导入的 skill_trees.json 文件"
        nameFilters: ["JSON 文件 (*.json)"]
        fileMode: FileDialog.OpenFile
        currentFolder: Platform.StandardPaths.writableLocation(Platform.StandardPaths.DocumentsLocation)
        onAccepted: {
            var p = importFileDialog.selectedFile || importFileDialog.fileUrl
            if (p) {
                var ok = skillModel.importSkillTrees(p)
                fileOpResultDialog.message = ok ? "导入成功" : "导入失败"
                fileOpResultDialog.open()
            }
        }
    }

    Dialog {
        id: fileOpResultDialog
        property string message: ""
        title: "文件操作"
        anchors.centerIn: parent
        width: 260
        height: 160
        modal: true
        Column {
            anchors.fill: parent
            anchors.margins: 20
            spacing: 15
            Text { text: fileOpResultDialog.message; font.pixelSize: 14; horizontalAlignment: Text.AlignHCenter; anchors.horizontalCenter: parent.horizontalCenter }
            Button { text: "确定"; anchors.horizontalCenter: parent.horizontalCenter; onClicked: fileOpResultDialog.close() }
        }
    }
}
